var express = require('express');
var router = express.Router();
var crypto = require('crypto');
var User = require('../models/user.js');
/* GET home page. */
// router.get('/', function(req, res, next) {
//   res.render('index', { title: 'Express' });
// });

router.get('/', function(req, res){
	res.render('index',{title:'首页'});
});
router.get('/u/:user',function (req, res) {
	res.render('user');
});
router.post('/post', function (req, res) {
	res.render('post');
});
router.get('/reg', function (req, res) {
	res.render('reg',{title:"用户注册"});
});
router.post('/reg', function (req, res) {
	if(req.body['password-repeat'] != req.body['password']){
		req.flash('error','两次输入不一致');
		return res.redirect('/reg');
	}
	var md5 = crypto.createHash('md5');
	var password = md5.update(req.body.password).digest('base64');
	var newUser = new User({
		name:req.body.username,
		password:password
	});

	// 检查用户名是否已经存在
	User.get(newUser.name,function(err, user){
		if(user){
			err = '用户名已经存在';
		}
		if(err){
			req.flash('error',err);
			return res.redirect('/reg');
		}
		// 不存在，创建新用户
		newUser.save(function(err){
			if(err){
				req.flash('error',err);
				return res.redirect('/reg');
			}
			req.session.user = newUser;
			req.flash('success','成功');
			req.redirect('/');
		})
	})


});
router.get('/login', function (req, res) {
	res.render('login');
});
router.post('/login', function (req, res) {
	res.render('doLogin');
});
router.get('/logout', function (req, res) {
	res.render('logout');
});











module.exports = router;
